package nz.ac.massey.cs.persistency;


import java.io.*;
import java.util.HashMap;
import java.util.Map;
//reads a file and gives to logic layer the sudoku info
public class Sudoku_reader 
{
	public static Sudoku_reader reader = null;

	public Sudoku_reader(){}

	/*
	 * get the instance of sudoku reader
	 */
	public static Sudoku_reader getInstance()
	{
		if(reader == null)
		{
			reader = new Sudoku_reader();
		}
		return reader;
	}

	/*
	 * get the sudoku's information from a file
	 */
	public result loadfile(String fileName)
	{
		File file = new File(fileName);
		int check;
		StringBuffer stringContent = new StringBuffer("");
		FileInputStream fileinput = null;
		try 
		{

			fileinput = new FileInputStream(file);
			while ((check = fileinput.read()) != -1)
				stringContent.append((char) check);
			fileinput.close();

		} 
		catch (Exception e) 
		{
			System.out.println(e);
		}

		String filecontents = stringContent.toString(); 
		String dividedata = "[;]"; 
		String dividetype = "[,]";   
		String dividecells = "[,]"; 
		String divideconstraint = "[!]";

		filecontents = filecontents.replace("\r", "");
		filecontents = filecontents.replace("\n", "");
		filecontents = filecontents.replace(" ", "");
		String dividedinfo[] = filecontents.split(dividedata);

		String[] typeInfo = dividedinfo[0].split(dividetype);
		Map<String,String> typeInfoMap = new HashMap<String, String>();
		for(int i =0;i < typeInfo.length;i++)
		{
			String[] data = typeInfo[i].split("=");
			typeInfoMap.put(data[0], data[1]);
		}

		int lengthofrow = Integer.parseInt(typeInfoMap.get("SizeX"));
		int lengthofcol = Integer.parseInt(typeInfoMap.get("SizeY"));

		String[][] cellInfo = new String[lengthofrow][lengthofcol];	
		String[] cells = dividedinfo[1].split(dividecells);

		int count = 0;
		if(cells.length == 1)
		{
			cells = dividedinfo[1].split("");
			count = 1;
		}

		for(int i=0;i<lengthofrow;i++)
		{
			for(int j=0; j<lengthofcol;j++)
			{
				cellInfo[i][j]=cells[count]; 
				count++;
			}
		}

		String[] constraintInfo = new String[2];
		if( dividedinfo.length ==3)
		{
			constraintInfo = dividedinfo[2].split(divideconstraint);
		}	    

		return new result(cellInfo, constraintInfo,typeInfoMap);  	 
	}

	public class result
	{
		private String[][] cellInfo;
		private String[] constraintInfo;
		Map<String,String> typeInfo;


		public result(String[][] cellInfo,String[] constraintInfo,Map<String,String> typeInfo)
		{
			this.cellInfo = cellInfo;
			this.constraintInfo = constraintInfo;
			this.typeInfo = typeInfo;
		}

		public String[][] getCellInfo() {
			return cellInfo;
		}

		public String[] getConstraintInfo() {
			return constraintInfo;
		}   	 

		public Map<String,String> getTypeInfo()
		{
			return typeInfo;
		}
	}     
}

